const express = require('express')
const router = express.Router()
const { approvalModel, userModel, branchModel } = require('../model/models')
//获取自己提交的申请和需要自己审核的申请 
router.get('/approval', async (req, res) => {
    let id = req.user.user
    let query = req.query
    let data = await approvalModel.find({
        $or: [
            { u_id: id },
            { checker: id }
        ]
    }
    ).populate('u_id').populate('checker').exec()
    console.log(query);
    if (query.state!= '[]' & query.type != 'wu') {
        data = data.filter(item => {
            return JSON.parse(query.state).includes(item.state) & item.type == query.type
        })
    }else if(query.state!= '[]' & query.type == 'wu'){
        data = data.filter(item => {
            return JSON.parse(query.state).includes(item.state)
        })
    }else if(query.state== '[]' & query.type != 'wu'){
        data = data.filter(item => {
            return item.type == query.type
        })
    }
    res.send({
        code: 200,
        data
    })
})
// 添加申请
router.post('/upapproval', async (req, res) => {
    let body = req.body
    let id = req.user.user;
    let user = await userModel.findOne({ _id: id }).exec()
    let breach = await branchModel.findOne({ $or: [{ _id: user.b_id }, { responsible: user._id }] }).exec()
    // 他不是部门负责人
    if (!user.b_id) {
        // 他是部门负责人
        if (breach.b_id) {
            // b_id存在则说明他有上级
            breach = await branchModel.findOne({ _id: breach.b_id }).exec()
        } else {
            breach = await branchModel.findOne({ b_name: '总裁办' }).exec()
        }
    }
    body.checker = breach.responsible
    body.u_id = id
    await approvalModel.create(body)
    res.send({
        code: 200,
        msg: '申请提交成功'
    })
})

// 修改
router.patch('/editapproval', async (req, res) => {
    let body = req.body
    await approvalModel.updateOne({ _id: body.id }, body)
    res.send({
        code: 200,
        msg: '修改成功'
    })
})


module.exports = router